<script setup lang='ts'>
import type { EnumCurrencyKey } from '~/apis/types'
import { currencyConfig } from '~/composables/useCurrencyData'
import { useDialogSelectCurrency } from '~/dialogs/useDialogSelectCurrency'
import { useDialogShare } from '~/dialogs/useDialogShare'


interface Props {
  isTheatre: boolean
  id: string
  pid: string
  gameId: string
  vid?: string
}
defineOptions({
  name: 'AppCasinoIframe',
})
const props = defineProps<Props>()
const emit = defineEmits(['changeTheatre', 'gameDetailsChange'])
const appStore = useAppStore()
const { userInfo } = storeToRefs(appStore)
const { t } = useI18n()
const { isMobile,  bodyWidth } = storeToRefs(useWindowStore())
const { isLogin, currentGlobalCurrency, isCompleteKYC } = storeToRefs(useAppStore())
const { isKYCVerifyOpen } = storeToRefs(useBrandStore())
const { allPlatformList } = storeToRefs(useCasinoStore())

const { openDialogSelectCurrency } = useDialogSelectCurrency()
const { openDialogShare } = useDialogShare()

const {
  bool: isShowFrameOverlay,
  setTrue: overlayTrue,
  setFalse: overlayFalse,
} = useBoolean(false)
const { bool: isRealMoneyMode, setBool: setRealModeBool } = useBoolean(isLogin.value)
// const { bool: isTrendOpen, toggle: toggleTrendOpen } = useBoolean(false)
// 余额箭头
const {
  bool: isCurrencyOpen1, setTrue: setCurrencyOpen1,
  setFalse: setCurrencyClose1,
} = useBoolean(false)
const {
  bool: isCurrencyOpen2, setTrue: setCurrencyOpen2,
  setFalse: setCurrencyClose2,
} = useBoolean(false)
const {
  bool: isCurrencyOpen3, setTrue: setCurrencyOpen3,
  setFalse: setCurrencyClose3,
} = useBoolean(false)
const {
  bool: isShowIframe,
  setTrue: showIframe,
  setFalse: hideIframe,
} = useBoolean(false)
const {
  bool: isShowIframeDoc,
  setTrue: showIframeDoc,
  setFalse: hideIframeDOc,
} = useBoolean(false)
const { bool: showTestMode } = useBoolean(false)
/** KYC弹窗 */
/* const { openKYCDialog } = useDialogKYCVerify() */
// const { bool: isShowMobileTopOperation, setTrue: showMobileTopOperation, setFalse: hideMobieTopOperation } = useBoolean(false)

const currentCurrency = ref<EnumCurrencyKey>('CNY')
const currencyList = ref<EnumCurrencyKey[]>([])
const gameFrameRef = ref()
const { bool: isFavorite } = useBoolean(false)
const { bool: realModeLoading } = useBoolean(false)
const { bool: testModeLoading } = useBoolean(false)
// const mobileGameFrameRef = ref()
const mobileGameUrl = ref()

const paramEmpty = computed(() => {
  return !!(props.id || props.gameId)
})
const exclude = computed(() => {
  return userInfo.value?.exclude === 1
})
// 游戏数据接口
const {
  data: dataDetail,
  runAsync: runDetail,
} = useRequest(() => {
  return ApiMemberGameDetail(props.id, props.pid, props.gameId)
}, {
  ready: paramEmpty,
  onSuccess(res) {
    if (res.game_type === EnumGlobalGameType.slot)
      showTestMode.value = true

    currencyList.value = res.currencys

    // 如果用户选择过货币，使用之前保存的货币
    const lastCurrency = Local.get<EnumCurrencyKey>(STORAGE_CASINO_GAME_CURRENCY)

    if (lastCurrency && currencyList.value.findIndex(a => a === lastCurrency.value) > -1)
      currentCurrency.value = lastCurrency.value

    else if (currencyList.value.findIndex(a => a === currentGlobalCurrency.value) > -1)
      currentCurrency.value = currencyList.value[currencyList.value.findIndex(a => a === currentGlobalCurrency.value)]

    else
      currentCurrency.value = currencyList.value[0]

    isFavorite.value = +res.is_fav === 1
    overlayTrue()
    emit('gameDetailsChange', res)
  },
})
// 分享相关
const { runAsync: runAgencyCheck } = useRequest(ApiMemberAgencyCheck, { manual: true })
const globalCurrencyCode = computed(() => {
  if (isLogin.value)
    return application.isVirtualCurrency(currentGlobalCurrency.value) ? currencyConfig.USDT.cur : currencyConfig[currentGlobalCurrency.value].cur

  return undefined
})

const id = computed(() => dataDetail.value ? dataDetail.value.id : '')
const pid = computed(() => dataDetail.value ? dataDetail.value.platform_id : '')
const code = computed(() => dataDetail.value ? dataDetail.value.game_id : '')
const currencyCode = computed(() => {
  return currentCurrency.value ? currencyConfig[currentCurrency.value].cur : '0'
})
const bigGameWrapper = computed(() => bodyWidth.value > 930)
const gameProviderName = computed(() => {
  return allPlatformList.value?.find(
    a => a.id === dataDetail.value?.platform_id,
  )?.name ?? '-'
})
// AG平台游戏
// AG   = "104" //AG真人
// AGFish  = "208" //AG捕鱼
// AGSlot       = "312" //AG老虎机(XIN)
// YOPLAY       = "316" //AG老虎机(YOPLAY)
// BBIN = "107" //BBIN真人
// BBINSlot     = "317" //BBIN老虎机
// IM  = "401" 优化代码结构 直接加在AG判断
const isAG = computed(() => (pid.value === '312' || pid.value === '104' || pid.value === '208' || pid.value === '312' || pid.value === '316' || pid.value === '107' || pid.value === '317' || pid.value === '401'))

onMounted(() => {
  if (exclude.value)
    return //openNotify({ type: 'error', title: t('submit_error'), message: t('exclude_off_notify') })
})

// 启动游戏接口
const {
  run: runLunchGame,
  runAsync: runLunchGameAsync,
  data: gameUrl,
  mutate: mutateGameUrl,
} = useRequest(() => {
  if (exclude.value)
    throw new Error(' ')
  return ApiGameLunch({
    pid: pid.value,
    code: code.value,
    cur: currencyCode.value,
    wcur: getCurrencyConfig(currentGlobalCurrency.value).cur,
  })
}, {
  manual: true,
  onBefore() {
    if (isRealMoneyMode.value)
      realModeLoading.value = true

    else
      testModeLoading.value = true
  },
  onSuccess(res) {
    // 判断data开头是不是http
    if (res.toString().startsWith('http')) {
      // H5模式直接打开游戏
      console.log(dataDetail)

      if (isMobile.value) {
        if (isAG.value) {
          setTimeout(() => {
            location.href = res
          }, 100)
        }
        else {
          mobileGameUrl.value = res
          localStorage.setItem('gameUrlLocal', res)
          i18nNavigateTo('/casino/mobile-game-frame')
        }
        // location.href = res
        setTimeout(() => {
          resetH5Loading()
        }, 1500)
      }
      else {
        showIframe()

      }
    }
    else {
      if (isMobile.value) {
        handlePgGameStrToLink(res).then((res) => {
          if (isAG.value)
            location.href = res || ''
          else
            mobileGameUrl.value = res
          // showIframe()
          localStorage.setItem('gameUrlLocal', res)
          i18nNavigateTo('/casino/mobile-game-frame')
          // i18nNavigateTo(`/casino/mobile-game-frame?gameUrl=${encodeURIComponent(res)}`)
          resetH5Loading()
        })

      }
      else {
        showIframeDoc()
      }
    }
  },
  onError() {
    resetH5Loading()
  },
})
//
function resetH5Loading() {
  realModeLoading.value = false
  testModeLoading.value = false
}
// pc自动启动游戏
function autoLunchOnPc() {
  !isMobile.value && isLogin.value && runLunchGame()
}
// 重新获取游戏地址是先清空
function clearUrl() {
  hideIframe()
  hideIframeDOc()
  mutateGameUrl('')
}
// 切换路由时重新获取detail
function refreshDetail() {
  clearUrl()
  runDetail().then(() => !isAG.value && autoLunchOnPc())
}
// 选择货币
function onChooseCurrency(v: EnumCurrencyKey) {
  clearUrl()
  currentCurrency.value = v
  Local.set<EnumCurrencyKey>(STORAGE_CASINO_GAME_CURRENCY, v)
  overlayTrue()
  autoLunchOnPc()
}
// 切换试玩真钱模式
function onSwitchRealMoneyMode(v: boolean) {
  /** 增加kyc逻辑 */
  if (isLogin.value && isKYCVerifyOpen.value && !isCompleteKYC.value)
    return //openKYCDialog()

  setRealModeBool(v)
  overlayFalse()
  if (isMobile.value || isAG.value) {
    // pg === '301'
    if (props.vid === '301') {
      runLunchGameAsync().then((res) => {
        // 1. 伪装跳转
        history.pushState(null, '', '/virtual.html')
        // 2. 替换整个页面
        document.open()
        document.write(res)
        document.close()

        resetH5Loading()
      })
    }
    else {
      runLunchGame()
    }
  }
}
// 全屏
function onClickFullScreen() {
  gameFrameRef.value.requestFullscreen()
}
// 剧院
function onClickTheatre() {
  emit('changeTheatre', !props.isTheatre)
}

// 添加收藏
const { run: runFavInsert } = useRequest(() => ApiMemberFavInsert(id.value), {
  onSuccess() {
    isFavorite.value = true
  },
})
// 删除收藏
const { run: runFavDelete } = useRequest(() => ApiMemberFavDelete(id.value), {
  onSuccess() {
    isFavorite.value = false
  },
})
function onClickFavorite() {
  if (isFavorite.value)
    return runFavDelete()
  runFavInsert()
}

// 点击判断是否已登陆
function onClickMaybeNotLogin(type: 'fav' | 'share') {
  if (!isLogin.value)
    return i18nNavigateTo('/login/regist')

  switch (type) {
    case 'fav':
      onClickFavorite()
      break
    case 'share':
      openDialogShare()
  }
}

watch(currentGlobalCurrency, (a) => {
  const index = currencyList.value.findIndex(c => c === a)
  if (index > -1) {
    currentCurrency.value = currencyList.value[index]
    onChooseCurrency(currentCurrency.value)
  }
})

/** 处理因缓存而导致游戏会话失效问题 */
const isFirstActivate = ref(true)
onActivated(() => {
  if (isFirstActivate.value) {
    isFirstActivate.value = false
    return
  }
  !isAG.value && autoLunchOnPc()
})

defineExpose({ refreshDetail, dataDetail })
await application.allSettled([runDetail().then(() => !isAG.value && autoLunchOnPc())])

</script>

<template>
<div id="game-full-layout" class="mx-auto py-2 sm:py-0 grid-cols-1">
    <div class="bg-bg-black-3 rounded-xl">
      <div class="flex items-center gap-3 p-4 bg-bg-black-4 rounded-tl-xl rounded-tr-xl">
            <BaseImage :url="dataDetail?.img || ''" is-cloud class="overflow-hidden w-32 h-42 rounded-[.25rem]" />
        <div class="flex flex-col gap-2 h-full flex-1 min-w-0">
          <div v-if="isLogin" class="flex flex-col justify-center items-left gap-2">
              <div class="sm:flex sm:flex-row sm:items-center sm:justify-center">
                <span class="text-white-0 leading-[1.125rem] text-xs font-bold">
                  {{ $t('used_currency') }}
                </span>
                <BaseButton  @click="openDialogSelectCurrency" type="none" class="p-0 sm:flex-1 sm:ml-2 w-full bg-bg-black-5 mt-2 md:mt-0">
                  <div class="flex items-center justify-start p-1 text-white-0 whitespace-nowrap relative w-full sm:h-10 text-xs">
                    <AppCurrencyIcon show-name :currency-type="currentCurrency" class="center"/>
                    <span class="text-[.625rem] text-white-0 whitespace-nowrap">&nbsp;({{ $t('deposit_balance') }})</span>
                    <div class="bg-bg-black-6 size-6 flex items-center justify-center rounded-md absolute right-1">
                      <BaseIcon name="uni-arrow-down" />
                    </div>
                  </div>
                </BaseButton>
              </div>
          </div>
          <div v-else class="mb-16 flex flex-col items-start">
            <span class="text-white-0 leading-[1.125rem] text-xs font-bold">
              {{ dataDetail?.name }}
            </span>
            <BaseButton type="none" class="h-4 px-0">
              <span class="text-text-white-2 text-[.625rem] font-extrabold truncate" @click="i18nNavigateTo(`/casino/group/provider?vid=${vid}`)">
                {{ gameProviderName }}
              </span>
            </BaseButton>
          </div>
          <BaseButton
            v-if="isLogin" :loading="realModeLoading"
             :disabled="exclude" @click="onSwitchRealMoneyMode(true)"
          >
             <BaseIcon name="game-start" />
            <span class="ml-2">{{ t('casino_inside_start_game_button') }}</span>
          </BaseButton>
          <BaseButton v-else  @click="i18nNavigateTo('/login/regist')">
            <span class="reg-text">{{ t('regist') }}</span>
          </BaseButton>
        </div>
      </div>
      <div class="px-4 py-[.625rem] flex items-end justify-between border-t border-[#e4eaf019] text-[1.5rem]">
        <div class="flex items-center gap-4"></div>
        <div class="flex items-center gap-4">
            <!-- 收藏游戏 -->
            <BaseIcon name="game-fav" :class="{ 'active': isFavorite }"  @click="onClickMaybeNotLogin('fav')"/>
            <BaseIcon name="game-share" @click="onClickMaybeNotLogin('share')"/>
        </div>
      </div>
    </div>
</div>
<div class="bg-bg-black-4 py-[.625rem] px-4 rounded-[.25rem] flex justify-between">
  <div class="flex flex-col">
    <span class="text-base leading-6 font-bold mb-0.5">{{ dataDetail?.name }}</span>
    <span class="cursor-pointer text-xs leading-[1.125rem] text-brand" @click="i18nNavigateTo(`/casino/group/provider?vid=${vid}`)">
      {{ gameProviderName }}
    </span>
  </div>
  <div v-if="+(dataDetail?.rtp || 0) > 0" class="flex flex-col">
    <span class="text-base leading-6 font-bold mb-0.5">RTP</span>
    <span class="text-xs leading-[1.125rem] text-brand">{{ toFixed(dataDetail?.rtp || 0, 2) }}%</span>
  </div>
</div>

</template>

<style lang='scss' scoped>
#game-full-layout{
  --tg-app-currency-icon-spacing: .25rem;
  .active{
    --tg-base-icon-color: var(--color-function-orange);
  }
}
</style>
